package com.fc.commons.security;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.fc.commons.logger.UtilLogger;

public class MD5Util {
	private static final String KEY_MD5 = "MD5";
    
	private static MessageDigest md5_digest = null;
	
	private MD5Util(){
		try {
			if(md5_digest == null){
				md5_digest = MessageDigest.getInstance(KEY_MD5);
			}
				
		} catch (NoSuchAlgorithmException e) {
			UtilLogger.instance().getLogger().error(e.getMessage(),e);
		}
	}
	
	public static class Instance{
		public static MD5Util getInstance(){
			return new MD5Util();
		}
	}
	
	public String md5(String source){
		if(md5_digest == null){
			throw new NullPointerException("MD5 algorithm init failed");
		}
		return SGlobalUtil.INSTANCE.bytes2String(md5_digest.digest(source.getBytes()));
	}
	
	public String md5(byte[] source){
		if(md5_digest == null){
			throw new NullPointerException("MD5 algorithm init failed");
		}
		return SGlobalUtil.INSTANCE.bytes2String(md5_digest.digest(source));
	}
	
	/**
	 * 23位MD5
	 * @param source
	 * @return
	 */
	public String md5TO23Bit(String source){
		try {  
			if(md5_digest == null){
				throw new NullPointerException("MD5 algorithm init failed");
			}
            return SGlobalUtil.INSTANCE.bytes2String(md5_digest.digest(source.getBytes(SecurityConst.DEFALUT_CODEC)))  
                    .substring(3, 26);
        } catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return source;
	}
}
